<template>
  <div class="user-management">
    <h2>{{ $t('message.userManagement') }}</h2>
    
    <div class="user-actions">
      <el-button type="primary" @click="openAddUserDialog">{{ $t('message.addUser') }}</el-button>
    </div>
    
    <el-table
      :data="users"
      style="width: 100%"
      :default-sort="{ prop: 'createdAt', order: 'descending' }"
      table-layout="fixed"
    >
      <el-table-column :label="$t('message.username')" width="120" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.username }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.email')" width="200" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.email }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.role')" width="120" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ getRoleName(scope.row.roleId) }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.status')" width="100" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">
            <el-tag 
              :type="scope.row.status === 'ACTIVE' ? 'success' : 'danger'"
              disable-transitions
            >
              {{ scope.row.status === 'ACTIVE' ? $t('message.active') : $t('message.inactive') }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.createdAt')" width="180" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ formatDate(scope.row.createdAt) }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.actions')" width="300" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">
            <el-button size="small" @click="editUser(scope.row)">{{ $t('message.edit') }}</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 'ACTIVE' ? 'warning' : 'success'"
              @click="toggleUserStatus(scope.row)"
            >
              {{ scope.row.status === 'ACTIVE' ? $t('message.deactivate') : $t('message.activate') }}
            </el-button>
            <el-button size="small" type="primary" @click="resetPassword(scope.row)">{{ $t('message.resetPassword') }}</el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row.userId)">{{ $t('message.delete') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="120px">
        <el-form-item :label="$t('message.username')" prop="username">
          <el-input 
            v-model="userForm.username" 
            :placeholder="$t('message.pleaseEnterUsername')"
            :disabled="isEdit"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.email')" prop="email">
          <el-input 
            v-model="userForm.email" 
            :placeholder="$t('message.pleaseEnterEmail')"
            :disabled="isEdit"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.role')" prop="roleId">
          <el-select v-model="userForm.roleId" :placeholder="$t('message.pleaseSelectRole')" style="width: 100%">
            <el-option
              v-for="role in roles"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!isEdit" :label="$t('message.password')" prop="password">
          <el-input 
            v-model="userForm.password" 
            type="password"
            :placeholder="$t('message.pleaseEnterPassword')"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isEdit" :label="$t('message.confirmPassword')" prop="confirmPassword">
          <el-input 
            v-model="userForm.confirmPassword" 
            type="password"
            :placeholder="$t('message.pleaseConfirmPassword')"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.status')" prop="status">
          <el-select v-model="userForm.status" :placeholder="$t('message.pleaseSelectStatus')" style="width: 100%">
            <el-option :label="$t('message.active')" value="ACTIVE" />
            <el-option :label="$t('message.inactive')" value="INACTIVE" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('message.cancel') }}</el-button>
          <el-button type="primary" @click="saveUser">{{ $t('message.confirm') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

export default {
  name: 'UserManagement',
  setup() {
    const { t } = useI18n();
    const authStore = useAuthStore();
    
    // 用户数据
    const users = ref([]);
    const roles = ref([]);
    
    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const isEdit = ref(false);
    
    // 表单数据
    const userForm = reactive({
      userId: '',
      username: '',
      email: '',
      roleId: '',
      password: '',
      confirmPassword: '',
      status: 'ACTIVE'
    });
    
    const userFormRef = ref();
    
    // 表单验证规则
    const userRules = {
      username: [
        { required: true, message: t('message.pleaseEnterUsername'), trigger: 'blur' },
        { min: 3, max: 20, message: t('message.usernameLength'), trigger: 'blur' }
      ],
      email: [
        { required: true, message: t('message.pleaseEnterEmail'), trigger: 'blur' },
        { type: 'email', message: t('message.emailFormatError'), trigger: 'blur' }
      ],
      roleId: [
        { required: true, message: t('message.pleaseSelectRole'), trigger: 'change' }
      ],
      password: [
        { required: !isEdit.value, message: t('message.pleaseEnterPassword'), trigger: 'blur' },
        { min: 6, message: t('message.passwordLength'), trigger: 'blur' }
      ],
      confirmPassword: [
        { required: !isEdit.value, message: t('message.pleaseConfirmPassword'), trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== userForm.password) {
              callback(new Error(t('message.passwordMismatch')));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ]
    };
    
    // 获取用户列表
    const loadUsers = async () => {
      try {
        const response = await fetch('/api/admin/users', {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          const userData = await response.json();
          
          // 规范化用户数据以确保与表格列定义匹配
          users.value = userData.map(user => ({
            userId: user.userId || user.user_id || user.id || user.userUuid,
            username: user.username || user.name,
            email: user.email,
            roleId: user.roleId || user.role_id || user.role,
            status: user.status,
            createdAt: user.createdAt || user.created_at || user.createTime || user.create_time,
            updatedAt: user.updatedAt || user.updated_at || user.updateTime || user.update_time,
            lastLoginAt: user.lastLoginAt || user.last_login_at || user.lastLoginTime,
            phone: user.phone || user.phoneNumber,
            avatar: user.avatar || user.avatar_url,
            userType: user.userType || user.user_type
          }));
        } else {
          ElMessage.error(t('message.failedToLoadUsers'));
        }
      } catch (error) {
        console.error('Error loading users:', error);
        ElMessage.error(t('message.failedToLoadUsers'));
      }
    };
    
    // 获取角色列表
    const loadRoles = async () => {
      try {
        const response = await fetch('/api/admin/roles', {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          roles.value = await response.json();
        }
      } catch (error) {
        console.error('Error loading roles:', error);
      }
    };
    
    // 打开添加用户对话框
    const openAddUserDialog = () => {
      isEdit.value = false;
      dialogTitle.value = t('message.addUser');
      resetForm();
      dialogVisible.value = true;
    };
    
    // 编辑用户
    const editUser = (user) => {
      isEdit.value = true;
      dialogTitle.value = t('message.editUser');
      // 复制用户数据到表单，确保属性映射正确
      Object.assign(userForm, {
        userId: user.userId || user.user_id || user.id || user.userUuid,
        username: user.username || user.name,
        email: user.email,
        roleId: user.roleId || user.role_id || user.role,
        status: user.status,
        phone: user.phone || user.phoneNumber,
        avatar: user.avatar || user.avatar_url,
        userType: user.userType || user.user_type
      });
      userForm.password = ''; // 编辑时不显示密码
      userForm.confirmPassword = '';
      dialogVisible.value = true;
    };
    
    // 删除用户
    const deleteUser = async (userId) => {
      try {
        await ElMessageBox.confirm(
          t('message.confirmDeleteUser'),
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        const response = await fetch(`/api/admin/users/${userId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          ElMessage.success(t('message.deleteUserSuccess'));
          loadUsers(); // 重新加载用户
        } else {
          ElMessage.error(t('message.deleteUserFailed'));
        }
      } catch (error) {
        console.error('Error deleting user:', error);
      }
    };
    
    // 切换用户状态
    const toggleUserStatus = async (user) => {
      try {
        const newStatus = user.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';
        const actionText = newStatus === 'ACTIVE' ? t('message.activate') : t('message.deactivate');
        
        await ElMessageBox.confirm(
          `${actionText} ${t('message.userConfirm')}?`,
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        // 更新用户状态
        const response = await fetch(`/api/admin/users/${user.userId}`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ ...user, status: newStatus })
        });
        
        if (response.ok) {
          ElMessage.success(`${actionText}${t('message.successSuffix')}`);
          loadUsers(); // 重新加载用户
        } else {
          ElMessage.error(`${actionText}${t('message.failureSuffix')}`);
        }
      } catch (error) {
        console.error('Error toggling user status:', error);
      }
    };
    
    // 重置用户密码
    const resetPassword = async (user) => {
      try {
        await ElMessageBox.prompt(
          t('message.resetPasswordPrompt'),
          t('message.resetPassword'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            inputPattern: /^.{6,}$/,
            inputErrorMessage: t('message.passwordLength')
          }
        ).then(async ({ value }) => {
          const response = await fetch(`/api/admin/users/${user.userId}/password`, {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ password: value })
          });
          
          if (response.ok) {
            ElMessage.success(t('message.resetPasswordSuccess'));
          } else {
            ElMessage.error(t('message.resetPasswordFailed'));
          }
        });
      } catch (error) {
        if (error !== 'cancel' && error !== 'close') {
          console.error('Error resetting password:', error);
        }
      }
    };
    
    // 保存用户
    const saveUser = async () => {
      try {
        await userFormRef.value.validate();
        
        // 检查密码确认
        if (!isEdit.value && userForm.password !== userForm.confirmPassword) {
          ElMessage.error(t('message.passwordMismatch'));
          return;
        }
        
        let response;
        if (isEdit.value) {
          // 更新用户，排除密码字段
          const { password, confirmPassword, ...updateData } = userForm;
          response = await fetch(`/api/admin/users/${userForm.userId}`, {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(updateData)
          });
        } else {
          // 创建用户
          const { confirmPassword, ...userData } = userForm;
          response = await fetch('/api/admin/users', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(userData)
          });
        }
        
        if (response.ok) {
          ElMessage.success(isEdit.value ? t('message.updateUserSuccess') : t('message.addUserSuccess'));
          dialogVisible.value = false;
          loadUsers(); // 重新加载用户
        } else {
          const errorData = await response.json();
          ElMessage.error(errorData.message || (isEdit.value ? t('message.updateUserFailed') : t('message.addUserFailed')));
        }
      } catch (error) {
        console.error('Error saving user:', error);
        ElMessage.error(isEdit.value ? t('message.updateUserFailed') : t('message.addUserFailed'));
      }
    };
    
    // 重置表单
    const resetForm = () => {
      Object.assign(userForm, {
        userId: '',
        username: '',
        email: '',
        roleId: '',
        password: '',
        confirmPassword: '',
        status: 'ACTIVE'
      });
    };
    
    // 根据角色ID获取角色名称
    const getRoleName = (roleId) => {
      if (!roles.value || !Array.isArray(roles.value)) {
        return roleId; // 如果roles未加载或不是数组，直接返回roleId
      }
      const role = roles.value.find(r => r.roleId === roleId);
      return role ? role.roleName : roleId;
    };
    
    // 格式化日期
    const formatDate = (dateValue) => {
      if (!dateValue) return '';
      
      let date;
      // 处理不同格式的日期值
      if (typeof dateValue === 'string') {
        // 如果是字符串，直接创建Date对象
        date = new Date(dateValue);
      } else if (typeof dateValue === 'object' && dateValue !== null) {
        // 如果是Date对象，直接使用
        date = dateValue;
      } else if (typeof dateValue === 'number') {
        // 如果是时间戳，创建Date对象
        date = new Date(dateValue);
      } else {
        return '';
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '';
      }
      
      return date.toLocaleString();
    };
    
    onMounted(async () => {
      await Promise.all([
        loadUsers(),
        loadRoles()
      ]);
    });
    
    return {
      users,
      roles,
      dialogVisible,
      dialogTitle,
      userForm,
      userFormRef,
      userRules,
      openAddUserDialog,
      editUser,
      deleteUser,
      toggleUserStatus,
      resetPassword,
      saveUser,
      getRoleName,
      formatDate
    };
  }
};
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.user-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.table-cell-content {
  text-align: left;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* 确保Element Plus表格内容左对齐 */
:deep(.el-table .cell) {
  text-align: left;
  padding-left: 10px;
}

/* 确保表格内容不会居中对齐 */
:deep(.el-table) {
  table-layout: fixed;
}

:deep(.el-table__body-wrapper) {
  text-align: left;
}
</style>